// index.ts
// 获取应用实例
import msg from "../../utils/msg";
import User from "../../utils/user";

import { mergeSeparation, SignIn, Init } from "../../utils/request/api";
import { Course } from "../curriculum/interface";
import { SignParamActivity, SignParamCourse, goToSignInActivity, goToSignInCourse, _checkLocation, courseSignRes, activitySignRes, checkCourseType } from "../signIn/util";
import { signDetail } from "../signIn/interface";
const app = getApp<IAppOption>();
interface card {
    sr_id: number,
    id: number | string,
    title: string,
    content: string,
    date: string,
    times: string,//第几节上下课 用于checkSeparation函数
    sort: string,//第几节上课，用于排序
    type: string,
    s_type: '课程' | '活动',
    signDetail: signDetail,
}
interface Activity {
    id: number,
    name: string,
    location: string,
    a_start: string,
    a_end: string,
    sr_id: number,
    signDetail: signDetail,
    type: string,
    s_type: '课程' | '活动',
}
export {
    Activity,
}
Page({
    data: {
        user: {} as User,
        courseData: [
        ] as Array<card>,
        activityData: [
        ] as Array<card>,
        signData: [] as Array<card>,
        signCourse: [] as Array<Course>,
        //课程信息
        curriculum_msg: [] as Array<Course>,
        //活动信息
        activity_msg: [] as Array<Activity>,
        //学期开始日期
        startDate: "",
        //今天是学期的第几周
        nowWeeks: 0 as number,
        //今天是周几
        day: '' as string,
        //学生学号
        s_code: "",
        //是否正在获取地理位置
        gettingLocation: false,
    },

    // 去到签到详情
    goToSignIn(e: any) {
        let dataset = e.currentTarget.dataset;
        if (dataset.sign_type == '活动') {
            let data: SignParamActivity = {
                sign_type: dataset.sign_type,
                sr_id: dataset.sr_id,
                activity_msg: this._getOneActivityMsg(dataset.sr_id),
            };
            goToSignInActivity(data);
        }
        else if (dataset.sign_type == '课程') {
            let data: SignParamCourse = {
                sign_type: dataset.sign_type,
                sr_id: dataset.sr_id,
                course_msg: this._getOneCourseMsg(dataset.sr_id),
            };
            goToSignInCourse(data);
        }
    },
    //获取课程与活动数据
    init_data: async function (user: User) {
        let self = this;
        this.setData({
            user: user,
            s_code: user.code,
        });
        msg.Loading('获取个人信息中...')
        if (!user.cheakLogin()) {
            wx.switchTab({
                url: "/pages/user/user",
            });
            msg.hideLoading();
            msg.show('请先登录/注册', '并绑定个人信息');
            return;
        }
        //课程
        msg.Loading('加载中...');
        await Init({ code: user.code })
            .then((wx_res: any) => {
                //course
                let res_course = wx_res.data.data.course;
                self.setData({
                    curriculum_msg: res_course.course,//这一学期的课程信息
                    startDate: res_course.startDate,//学期第一天 其实没必要
                    nowWeeks: self._getWeekNumber(res_course.startDate),//计算这是开学第几周 其实没必要
                    day: self._convertToChinese(self._getDay().toString()),//计算今天是星期几
                });
                //设置全局变量
                app.globalData.nowWeeks = self._getWeekNumber(res_course.startDate);
                app.globalData.startDate = res_course.startDate;
                this.getTodayCourse(res_course.course);
                //course结束
                //activity
                let res_activtiy = wx_res.data.data.activity;

                this.setData({
                    activity_msg: res_activtiy.data,
                    activityData: this.getTodayActivity(res_activtiy.data),
                });
                //activity结束
                //获取正在签到数据
                this._getSignData(wx_res.data.data.signData);
            })
            .catch((res: any) => {
                console.log(res);
                msg.hideLoading();
                msg.show('加载失败', '可能是网络连接差或者服务器崩溃了，请稍后重试');
                return;
            });
        msg.hideLoading();
    },
    /**
    * @function 设置正在签到的数据，储存在signData里
    */
    _getSignData(signData: Array<Course | Activity>) {
        //console.log(new Date().getMilliseconds());
        let course = this.data.courseData;
        let activity = this.data.activityData;
        let sign: card[] = [];
        signData.forEach((item) => {
            course.forEach((c) => {
                if (c.sr_id == item.sr_id) sign.push(c);
            });
            activity.forEach((a) => {
                if (a.sr_id == item.sr_id) sign.push(a);
            });
        });
        this.setData({
            signData: sign,
        });
        //console.log(new Date().getMilliseconds());
    },
    onLoad: async function () {

    },

    onShow() {
        let user_temp = new User;
        if (!user_temp.cheakLogin()) {
            wx.switchTab({
                url: "/pages/user/user",
            });
            msg.hideLoading();
            msg.show('请先登录/注册', '并绑定个人信息');
            return;
        }
        this.setData({
            user: user_temp,
        });
        if (!user_temp.code) {
            return;
        }
        msg.Loading('正在获取今日课程与活动');
        this.init_data(user_temp);
        msg.hideLoading();
    },
    //跳转到课程表
    goToCurriculum() {
        if (!this.data.s_code) {
            msg.show('课程表请绑定学生信息后再使用', '');
            return;
        }
        //课程表只显示1-18周的课程，如果不在这个范围也要显示最近数据
        let nowWeeks = this.data.nowWeeks;
        if (nowWeeks < 1) nowWeeks = 1;
        if (nowWeeks > 18) nowWeeks = 18;
        let data = {
            curriculum_msg: this.data.curriculum_msg,
            startDate: this.data.startDate,
            nowWeeks: nowWeeks,
            day: this.data.day,
        };
        wx.switchTab({
            url: "/pages/curriculum/curriculum" + "?data=" + JSON.stringify(data),
            fail(res: any) {
                console.log(res)
            }
        })
    },
    goToActivityList() {
        wx.navigateTo({
            url: "/pages/activity/activity",
            fail(res: any) {
                console.log(res)
            }
        })
    },
    /**
  * @function 根据学期开始日期判断今天属于哪一周
  * @param {*startDate} 学期开始日期
  */
    _getWeekNumber(startDate: string): number {
        const today = new Date(); // 获取当前日期
        //console.log('startDate=',startDate);
        const inputDate = new Date(startDate);
        if (today > inputDate) {
            const timeDiff = Math.abs(today.getTime() - inputDate.getTime());
            const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)); // 计算日期差
            const groupNumber = Math.ceil(daysDiff / 7);
            if (groupNumber >= 18) {
                return 19;
            } else {
                //const groupNumber = Math.ceil(daysDiff / 7);
                return groupNumber;
            }
        } else {
            return 0;
        }
    },
    /**
    * @function 获取今天是周几
    */
    _getDay(): number {
        const today = new Date().getDay();
        // 因为返回值范围是 0-6，需要将星期天（0）转换为 7
        return today !== 0 ? today : 7;
    },
    /**
    * @function 将阿拉伯数字转换为简体中文数字
    */
    _convertToChinese(number: string) {
        var chineseNumber = number;
        switch (number) {
            case '1':
                chineseNumber = '一';
                break;
            case '2':
                chineseNumber = '二';
                break;
            case '3':
                chineseNumber = '三';
                break;
            case '4':
                chineseNumber = '四';
                break;
            case '5':
                chineseNumber = '五';
                break;
            case '6':
                chineseNumber = '六';
                break;
            case '7':
                chineseNumber = '七';
                break;
        }
        return chineseNumber;
    },
    /**
    * @function 将Course[]数据改写成card[]数据
    */
    _getCourseCard(course: Course[]): Array<card> {
        let nowWeeks = this.data.nowWeeks;
        if (nowWeeks < 1 || nowWeeks > 18) return [];
        let day = this.data.day;
        let cardData = [] as Array<card>;
        course.forEach((item, index) => {
            //console.log('item.day=',item.day);
            item.day = this._convertToChinese(item.day);
            if (item.day == day && item.week == nowWeeks) {
                let time = item.time.split('-');
                let temp: card = {
                    sr_id: item.sr_id,
                    id: item.id,
                    title: item.name,
                    times: item.time,
                    content: item.location + '-' + item.teacher,
                    date: this._getCourseStartTime(time[0]) + '-' + this._getCourseEndTime(time[1]),
                    sort: time[0],//用于排序
                    signDetail: item.signDetail,
                    type: item.type,
                    s_type: '课程',
                };
                cardData.push(temp);
            }
        });
        return this._sortArray(cardData);
    },
    /**
    * @function 获取这一周的课程
    */
    getTodayCourse(curriculum_msg: Course[]) {
        //已经知道今天是学期的第几周的周几，根据课程信息判断哪些课程要上
        //根据上课时间排序
        this.setData({
            courseData: this._getCourseCard(curriculum_msg),
        });
        //检查是否有分离数据
        this.checkSeparation();
    },
    /**
    * @function 活动改成特定形式
    */
    getTodayActivity(activity_msg: Activity[]): card[] {
        let activityData = [] as Array<card>;
        for (let index = 0; index < activity_msg.length; index++) {
            let element = activity_msg[index];
            if (this._isSameDay(element.a_start)) {
                let data: card = {
                    sr_id: element.sr_id,
                    id: element.id,
                    title: element.name,
                    content: element.location,
                    times: '',
                    date: this._combineDates(element.a_start, element.a_end),
                    sort: element.a_start,
                    signDetail: element.signDetail,
                    type: element.type,
                    s_type: '活动',
                };
                activityData.push(data);
            }
        }
        //根据开始时间排序
        return this._sortArrayByDate(activityData);

    },
    //更改日期格式
    _combineDates(date1: string, date2: string): string {
        const [date1Part, time1Part] = date1.split(" ");
        const [date2Part, time2Part] = date2.split(" ");

        const [year, month, day] = date1Part.split("-");
        const [hour, minute] = time1Part.split(":");
        const [hour2, minute2] = time2Part.split(":");

        return `${hour}:${minute}-${hour2}:${minute2}`;
    },

    //检查活动日期是否是今天
    _isSameDay(dateString: string): boolean {
        const inputDate = new Date(dateString);

        // 获取当前日期
        const today = new Date();
        const currentYear = today.getFullYear();
        const currentMonth = today.getMonth();
        const currentDay = today.getDate();

        // 获取输入日期的年、月、日
        const year = inputDate.getFullYear();
        const month = inputDate.getMonth();
        const day = inputDate.getDate();

        return (currentYear === year && currentMonth === month && currentDay === day);
    },
    /**
    * @function 当前时间是否在输入的这段时间内
    */
    _cheakTimeValid(startDate: string, endDate: string): boolean {
        const currentTime = new Date();
        const startDateTime = new Date(startDate);
        const endDateTime = new Date(endDate);
        return currentTime >= startDateTime && currentTime <= endDateTime;
    },
    _sortArrayByDate(arr: card[]): card[] {
        return arr.sort((a, b) => {
            const dateA = new Date(a.sort);
            const dateB = new Date(b.sort);
            return dateA.getTime() - dateB.getTime();
        });
    },
    /**
    * @function 检查这一周这门课上不上 (别忘了检查备注) //已经没必要了，工作由后端完成了
    */
    _checkRange(range: string, number: number): boolean {
        let ranges = range.split(",");
        let res = false;
        ranges.forEach((item) => {
            //console.log('_checkRange item=',item);
            //1.检查有没有(单)(双)的数据
            let item_temp = item;
            let note = '';
            if (item_temp.indexOf('(')) {
                note = item.slice(item.indexOf('(') + 1, item.indexOf(')'));
                //console.log('note=',note);
                item_temp = item.split('(')[0];
                //console.log('item_temp=',item_temp);
            }
            //2.检查是不是单独一周
            if (item_temp.length == 1) {
                item_temp = item_temp + '-' + item_temp;
            }
            let [start, end] = item_temp.split("-").map(Number);
            let num = number;
            if (Number.isNaN(start) || Number.isNaN(end) || Number.isNaN(num)) {
                throw new Error("Invalid input");
            }
            if (num >= start && num <= end) {
                //检查备注
                if (note == '双') {
                    res = (num % 2 == 0);
                }
                else if (note == '单') {
                    res = (num % 2 == 1);
                }
                else res = true;
            }
        })

        return res;
    },
    /**
    * @function 获取上课时间
    */
    _getCourseStartTime(index: string) {
        let time = '';
        switch (index) {
            case '1':
                time = '8:30';
                break;
            case '2':
                time = '9:20';
                break;
            case '3':
                time = '10:20';
                break;
            case '4':
                time = '11:10';
                break;
            case '5':
                time = '14:30';
                break;
            case '6':
                time = '15:20';
                break;
            case '7':
                time = '16:10';
                break;
            case '8':
                time = '16:50';
                break;
            case '9':
                time = '19:00';
                break;
            case '10':
                time = '19:50';
                break;
            case '11':
                time = '20:40';
                break;
        };
        return time;
    },
    /**
     * @function 获取下课时间
     */
    _getCourseEndTime(index: string) {
        let time = '';
        switch (index) {
            case '2':
                time = '10:00';
                break;
            case '3':
                time = '11:00';
                break;
            case '4':
                time = '11:50';
                break;
            case '5':
                time = '15:10';
                break;
            case '6':
                time = '16:00';
                break;
            case '7':
                time = '16:50';
                break;
            case '8':
                time = '17:40';
                break;
            case '9':
                time = '19:40';
                break;
            case '10':
                time = '20:30';
                break;
            case '11':
                time = '21:20';
                break;
        };
        return time;
    },
    /**
     * @function 课程列表按照sort属性排序
     */
    _sortArray(arr: card[]): card[] {
        return arr.sort((a, b) => parseInt(a.sort) - parseInt(b.sort));
    },
    /**
     * @function 通过sr_id从课程数组中拿取一条数据
     */
    _getOneCourseMsg(sr_id: number): Course {
        for (let i = 0; i < this.data.curriculum_msg.length; i++) {
            if (sr_id == this.data.curriculum_msg[i].sr_id) return this.data.curriculum_msg[i];
        }
        return {} as Course;
    },
    /**
     * @function 通过sr_id从活动数组中拿取一条数据
     */
    _getOneActivityMsg(id: number): Activity {
        for (let i = 0; i < this.data.activity_msg.length; i++) {
            if (id == this.data.activity_msg[i].sr_id) return this.data.activity_msg[i];
        }
        return {} as Activity;
    },
    //刷新
    reload() {
        this.onShow();
    },
    //休息一下吧~
    have_a_rest() {
        msg.show('今天没有课程哦~', '休息一下吧');
    },
    //休息一下吧2~
    have_a_rest2() {
        msg.show('今天没有活动哦~', '可以出去玩喽~');
    },
    /**
    * @function (已弃用，检查的功能由后端完成了)检查是否有连在一起缺分成两次签到的数据，若有则合并 如课程名称，教师，上课地点都相同同时时间上紧挨在一起的两条数据
    */
    checkSeparation() {
        let courseData = this.data.courseData;
        for (let i = 0; i < courseData.length; i++) {
            if ((i + 1) < courseData.length) {
                if ((courseData[i].title == courseData[i + 1].title) && (courseData[i].content == courseData[i + 1].content)) {
                    let temp1 = courseData[i].times.split('-');
                    let temp2 = courseData[i + 1].times.split('-');
                    //两门课时间紧挨一起
                    let t1 = parseInt(temp1[1]);
                    let t2 = parseInt(temp2[0]);
                    if ((t1 + 1) == t2) {
                        //合并数据
                        let self = this;
                        mergeSeparation({ c_id1: courseData[i].id, c_id2: courseData[i + 1].id })
                            .then((res: any) => {
                                console.log('mergeSeparation调用！ res=', res);
                                //this.getTodayCourse();
                            });
                    }
                }
            }
        }

    },
    //签到
    //signData中的数据已经验证过可以签到，所以省去了检测时间的环节
    async sign(e: any) {
        let data = e.currentTarget.dataset;
        let user = new User;
        if (!await _checkLocation(this, this.data.signData[0].signDetail).then((res) => { return true }).catch((res: any) => { console.log('reject!', res); return false; })) return;
        //checkLocation结束
        let res = await SignIn({ sr_id: data.sr_id, name: user.name, code: user.code, week: this.data.nowWeeks, type: '正常签到', s_type: data.s_type }).then((res: any) => { return res; });
        if (data.s_type == '课程'){
            if(!checkCourseType(this.data.signData[0].type))return;
            courseSignRes(res);
        }
        else if (data.s_type == '活动')
            activitySignRes(res);
    },

})
